<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;

/**
 * 出入库管理
 * @icon fa fa-exchange
 */
class StockTransaction extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\StockTransaction;
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model->where($where)->order($sort, $order)->paginate($limit);
            return json(["total" => $list->total(), "rows" => $list->items()]);
        }
        return $this->view->fetch();
    }

    /**
     * 审核出入库单
     */
    public function approve($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $row->status = 2;
                $row->approver_id = $this->auth->id;
                $row->approver_name = $this->auth->username;
                $row->approve_time = time();
                $row->save();

                // 更新库存
                $this->updateStock($row);

                Db::commit();
                $this->success('审核成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    private function updateStock($transaction)
    {
        $details = Db::name('scanwork_stock_transaction_detail')
            ->where('transaction_id', $transaction->id)
            ->select();

        foreach ($details as $detail) {
            $stock = Db::name('scanwork_stock')
                ->where('material_id', $detail['material_id'])
                ->where('warehouse_id', $transaction->target_warehouse_id)
                ->find();

            if ($transaction->transaction_type <= 3) { // 入库
                if ($stock) {
                    Db::name('scanwork_stock')
                        ->where('id', $stock['id'])
                        ->inc('quantity', $detail['quantity'])
                        ->update();
                } else {
                    Db::name('scanwork_stock')->insert([
                        'material_id' => $detail['material_id'],
                        'warehouse_id' => $transaction->target_warehouse_id,
                        'quantity' => $detail['quantity'],
                        'createtime' => time()
                    ]);
                }
            } else { // 出库
                if ($stock) {
                    Db::name('scanwork_stock')
                        ->where('id', $stock['id'])
                        ->dec('quantity', $detail['quantity'])
                        ->update();
                }
            }
        }
    }
}

